package com.im.common.packets.demo;

import java.io.ByteArrayInputStream;

import org.tio.utils.SystemTimer;

import com.googlecode.protobuf.format.JsonFormat;
import com.im.common.packets.ChatRespBody;
import com.im.common.packets.ChatType;

/**
 * @author Javen
 */
public class Test {

	public static void main(String[] args) {
//		int [] arr= {3,2,3,4,5,6,7,8};
//		System.out.println(array(arr));
		test();
	}
	
	

	
	public static void test() {
		try {
			JsonFormat jsonFormat = new JsonFormat();
			ChatRespBody.Builder builder = ChatRespBody.newBuilder();
			builder.setType(ChatType.CHAT_TYPE_PUBLIC);
			builder.setText("Javen 测试");
			builder.setFromId(1);
			builder.setFromNick("Javen");
			builder.setToId(110);
			builder.setToNick("Javen.zhou");
			builder.setGroup("Javen");
			builder.setTime(SystemTimer.currentTimeMillis());
			ChatRespBody chatRespBody = builder.build();
			//从protobuf转json
			String asJson = jsonFormat.printToString(chatRespBody);
			System.out.println("Object to json "+asJson);
			
			byte[] bodybyte = chatRespBody.toByteArray();
			//解码是从byte[]转换为java对象
			ChatRespBody parseChatRespBody = ChatRespBody.parseFrom(bodybyte);
			asJson = jsonFormat.printToString(parseChatRespBody);
			System.out.println("bodybyte to json "+asJson);
			
			//从json转protobuf
			ChatRespBody.Builder _builder = ChatRespBody.newBuilder();
			jsonFormat.merge(new ByteArrayInputStream(asJson.getBytes()), _builder);
			ChatRespBody _chatRespBody = _builder.build();
			asJson = jsonFormat.printToString(_chatRespBody);
			System.out.println("json to protobuf "+asJson);
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	
//	public static String array(int [] arry) {
//		StringBuffer sbf = new StringBuffer();
//		int length = arry.length;
//		if(length == 0) {
//			return "";
//		}
//		
//		if(length % 2 == 0 ) {
//			System.out.println("二的倍数");
//			sbf.append(getTwoNumber(arry));
//		}else {
//			int last = arry[length-1];
//			int first = arry[0];
//			//把最后一个元素替代指定的元素
////			arry[arry.length-1] = arry[arry.length-1];
//			//数组缩容
//			arry = Arrays.copyOf(arry, arry.length-1);
//			sbf.append(getTwoNumber(arry)).append(last).append(first);
//		}
//		return sbf.toString();
//	}
//	public static String getTwoNumber(int [] arry) {
//		StringBuffer sbf = new StringBuffer();
//		int length = arry.length / 2;
//		for (int i = 1; i <= length ; i++) {
//			int temp1= arry[i*2-2];
//			int temp2= arry[i*2-1];
//			sbf.append(temp1).append(temp2).append(" ");
//		}
//		return sbf.toString();
//	}
}
